<template>
    <div class="notification-page">
        <el-card class="!border-none" shadow="never">
            <el-page-header content="系统通知" @back="$router.back()" />
        </el-card>

        <el-card class="!border-none mt-4" shadow="never">
            <div class="notification-header">
                <div class="notification-stats">
                    <el-tag type="info">全部: {{ totalCount }}</el-tag>
                    <el-tag type="warning">未读: {{ unreadCount }}</el-tag>
                </div>
                <div class="notification-actions">
                    <el-button v-if="unreadCount > 0" type="primary" @click="markAllAsRead" :loading="markAllLoading">
                        全部标已读
                    </el-button>
                    <el-button type="primary" @click="delAsRead" :loading="markAllLoading">
                        删除已读
                    </el-button>
                    <el-button @click="refreshList" :loading="loading">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        刷新
                    </el-button>
                </div>
            </div>

            <el-table :data="notificationList" v-loading="loading" style="width: 100%">
                <el-table-column prop="title" label="状态" width="200">
                    <template #default="{ row }">
                        <div class="notification-title-cell">
                            <el-tag v-if="row.readed == 0" type="danger" size="small">未读</el-tag>
                            <el-tag v-else type="primary" size="small">已读</el-tag>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="content" label="内容">
                    <template #default="{ row }">
                        <div class="notification-content-cell" :title="row.msg">
                            {{ row.msg }}
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="created_at" label="时间" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.created_at) }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button v-if="row.readed === 0" type="primary" size="small" @click="markAsRead(row.id)"
                            :loading="markLoading === row.id">
                            标已读
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteNotification(row.id)"
                            :loading="deleteLoading === row.id">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="totalCount" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getMsgList, readed, deleteNotificationApi } from '@/api/notification'

interface Notification {
    id: number | string
    title: string
    content: string
    is_read: number
    created_at: string
    updated_at: string
}

const loading = ref(false)
const markAllLoading = ref(false)
const markLoading = ref<number | string | null>(null)
const deleteLoading = ref<number | string | null>(null)
const notificationList = ref<Notification[]>([])
const totalCount = ref(0)
const unreadCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 获取通知列表
const fetchNotifications = async () => {
    try {
        loading.value = true
        const response = await getMsgList({
            page_no: currentPage.value,
            page_size: pageSize.value
        })
        notificationList.value = response.lists || []
        unreadCount.value = response.unread_total
        totalCount.value = response.count

    } catch (error) {
        console.error('获取通知列表失败:', error)
        ElMessage.error('获取通知列表失败')
    } finally {
        loading.value = false
    }
}

// const deleteNotification = async (id: any) => {
//     let res = await deleteNotificationApi({ id: id })
//     if (res) {
//         fetchNotifications()
//     }
// }

const delAsRead = async () => {
    try {
        await ElMessageBox.confirm('确定要删除所有已读通知吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteNotificationApi({ all: 1 })

        fetchNotifications()

    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除通知失败:', error)
            ElMessage.error('删除通知失败')
        }
    } finally {
        deleteLoading.value = null
    }
}

// 删除通知
const deleteNotification = async (notificationId: number | string) => {
    try {
        await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteNotificationApi({ id: notificationId })

        fetchNotifications()

    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除通知失败:', error)
            ElMessage.error('删除通知失败')
        }
    } finally {
        deleteLoading.value = null
    }
}

const handleSizeChange = (e: any) => {
    pageSize.value = e
    fetchNotifications()
}

const handleCurrentChange = (e: any) => {
    currentPage.value = e
    fetchNotifications()
}

fetchNotifications()

const refreshList = () => {
    fetchNotifications()
}

// 标记为已读
const markAsRead = async (notificationId: number | string) => {
    console.log(notificationId, 'notificationIdnotificationIdnotificationId');
    try {
        markLoading.value = notificationId
        console.log(notificationId, 'notificationIdnotificationIdnotificationId');

        await readed({ id: notificationId })

        // 更新未读数量
        await fetchNotifications()

        ElMessage.success('已标记为已读')
    } catch (error) {
        console.error('标记已读失败:', error)
        ElMessage.error('标记已读失败')
    } finally {
        markLoading.value = null
    }
}


// 格式化时间
const formatTime = (timeStr: string) => {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 1) {
        return '刚刚'
    } else if (minutes < 60) {
        return `${minutes}分钟前`
    } else if (hours < 24) {
        return `${hours}小时前`
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return date.toLocaleDateString()
    }
}

// onMounted(() => {
//     fetchNotifications()
//     fetchUnreadCount()
// })
</script>

<style lang="scss" scoped>
.notification-page {
    .notification-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .notification-stats {
            display: flex;
            gap: 12px;
        }

        .notification-actions {
            display: flex;
            gap: 12px;
        }
    }

    .notification-title-cell {
        display: flex;
        align-items: center;
        gap: 8px;

        .notification-title-text {
            font-weight: 500;

            &.unread {
                color: #1890ff;
                font-weight: 600;
            }
        }
    }

    .notification-content-cell {
        color: #606266;
        line-height: 1.5;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .pagination-wrapper {
        margin-top: 20px;
        display: flex;
        justify-content: center;
    }
}
</style>